<template>
  <div v-show='!isBack'>
    <div class="shadowBox"></div>
    <div class="allContent">
      <div class="cardListTit">
        <span>可参与兑换的优惠券</span><i @click="isBackNow" class="iconfont icon-shanchu"></i>
      </div>
      <div class="cardListTit_coupon"
           v-infinite-scroll="moreList"
           infinite-scroll-disabled="loading"
           infinite-scroll-immediate-check="true"
           infinite-scroll-distance="100">
        <ul>
          <li class="cardCard" v-for="(item,index) in myCardList" v-show="item.type2=='default'" :key="index">
            <p class="cardCard_tit">{{item.mchtName}}</p>
            <div class="cardBg1">
              <div class="bgLine">
                <img src="../../images/cardBg_05.png">
              </div>
              <div class="cardBg2 white_bg">
                <div class="couponDiv"
                     :class="{'coupon_yellow':item.type=='cash','coupon_green':item.type=='rebate','coupon_blue':item.type=='voucher','coupon_orange':item.type=='present','coupon_purple':item.type=='ticket'}">
                  <!--<div class="couponDiv coupon_yellow">-->
                  <!--<div class="_num coupon_color_y">Coupon</div>-->
                  <div class="_num"
                       :class="{'coupon_color_y':item.type=='cash','coupon_color_g':item.type=='rebate','coupon_color_b':item.type=='voucher','coupon_color_o':item.type=='present','coupon_color_p':item.type=='ticket'}">
                    Coupon
                  </div>
                  <div class="_num_price">
                    <coupon-num :num="item.denomination" :type="item.type"></coupon-num>
                  </div>
                  <div class="coupon_type">{{item.type | couponTp}}</div>
                </div>
                <div class="card_info" @click="goCouponDetl(item)">
                  <div class="card_name">
                    {{item.name}}
                  </div>
                  <div class="coupon_info_item">
                    <p class="star_con">
                      <star :couponComScore="item.comScore"></star>
                    </p>
                    <p class="info_pad">{{item.comNum}}条 {{item.type | couponTp}}{{item.num}}张</p>
                  </div>

                  <div class="coupon_info_item color_gray">
                    已出售  {{item.soldnum}}  已使用 {{item.usednum}}
                  </div>
                  <i class="icon iconfont icon-right"></i>
                </div>
              </div>
              <div class="card_btn">
                <p class="card_btn_left"><span>{{item.valuation}}</span><span>芸券</span></p>
                <p class="count">
                  <span class='coupon_num' @click="add(index)">+</span>
                  <input readonly class='coupon_num' type="text" :value="index==currentIndex ? useCardNum : 0"/>
                  <span class='coupon_num' @click="reduce(index)">—</span>
                </p>
              </div>

            </div>
          </li>
        </ul>
      </div>
      <p v-show="noCard" class="noCard">没有可参与兑换的优惠券哦</p>

      <div class="exchange_btn2">
        <a href="javascript:;" class="btn_sure right" @click="btnOk">确定兑换</a>
        <div class="total">
          <!--<p class="total_all_top">估值<span>{{myCardList[currentIndex].valuation}}</span>云券抵用券<span>{{useCardNum}}</span>张</p>-->
          <p class="total_all_top">估值<span>{{cardValuetion}}</span>芸券
            <span v-show="this.cardType=='rebate'">折扣券</span>
            <span v-show="this.cardType=='cash'">代金券</span>
            <span v-show="this.cardType=='voucher'">抵用券</span>
            <span>{{useCardNum}}</span>张
            <!--<span>手续费</span><span style="color:#ec4e8a">{{fee}}云券</span>-->
          </p>
          <p class="total_all">{{theNeed}}<span>&nbsp;&nbsp;<span>{{paySum}}</span> 芸券</span></p>
        </div>
      </div>
      <no-data v-if="noInfo"></no-data>
      <div class="lastInfoMore" v-if="!moreInfo" v-show="myCardList.length>2" style="color:#fff;">没有更多</div>
      <div class="last_box" v-if="lastBox" v-show="myCardList.length!=0"></div>
    </div>
  </div>
</template>
<script>
  import getData from '../../service/getData.js';
  import getData4 from '../../service/getData4.js';
  import {mapState} from 'vuex'
  import star from './star.vue';
  import couponNum from './couponNum.vue'
  import CardList from "../../pages/center/cardList.vue";
  import {Storage} from 'src/utils/storage.js'

  import {
    Indicator,
    Toast,
  } from 'mint-ui'

  export default {
    data: function () {
      return {
        isBack: false,
        myCardList: '',
        useCardNum: 0,
        currentIndex: 0,
        status: false,
        payCardMchtId: '',
        payCardId: '',
        allClick: [9999, 9999],//初始化前后两次点击的卡券
        paySum: 0,//差值
        theNeed: "另需", //改变面板
        cardValuetion: 0,
        exCardInfo: {},
        denomination: 0,
        type: '',
        name: '',
        noCard: false,
        theShow: '支付',
        feeArray: [],
        fee: 0,//手续费
        currentPage: 0,
        noMoreCoupon: true,
        noInfo: false,
        moreInfo: true,
        loading: true,
        myCardListSinge: '',
        cardType: '',
        lastBox: false,

      }
    },
    props: {
      buyCardInfo: {
          type:Object,
          default:() => {}
      },
      tlrNo: {
        default:''
      },
      scanState: {
        type: Boolean,
        default: ''
      },
      inputAmt: {
        default: ''
      },
      inputNoSlae: {
        default: ''
      },
      inputDeskNum: {
        default: ''
      },
    },
    components: {
      star,
      couponNum
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo,
        myCoupon: state => state.center.myCoupon,
        couponsPageLimit: state => state.center.couponsPageLimit,
      })
    },

    created: function () {
      //console.log(this.buyCardInfo);
      this.paySum = this.buyCardInfo.allPayNum;
      this.moreList();
    },


    methods: {
      clickMoreList() {
        if (!this.noMoreCoupon) {//防止重复点击
          return
        }
        this.noMoreCoupon = false;
        this.currentPage = this.currentPage + 1;
        //console.log(this.currentPage)
        getData.cardToCardChange({
          method: 'post',
          data: {
            "aoData": JSON.stringify([{name: "iDisplayStart", value: this.currentPage}, {
              name: "iDisplayLength",
              "value": 10
            }])
          }//{"name":"iDisplayStart","value":1},{"name":"iDisplayLength","value":10}
        }, this.userInfo.usrId).then(rep => {
//                    console.log('券对券列表');
          //console.log(rep);
          if (rep.respCode == "00") {
            if (this.currentPage <= 1) {
              this.myCardList = rep.content.couponList;
            } else {
              this.myCardList = rep.content.couponList.concat(this.myCardList)
            }
            //如果没有符合条件的数据，显示没有数据
            if (rep.content.total <= 0) {
              this.noInfo = true;
            } else {
              this.noInfo = false;
            }
            if (rep.content.couponList) {
              if (rep.content.couponList.length < this.couponsPageLimit) {
                setTimeout(function () {
                  this.noMoreCoupon = true;
                }, 300);
                this.moreInfo = false;
                this.lastBox = true;
              }
              if (rep.content.couponList.length == this.couponsPageLimit) {//如果列表数据够10条，开启下拉加载
                this.moreInfo = true;
                this.loading = false;
                this.noMoreCoupon = true;
              }
            } else {
              setTimeout(function () {
                this.noMoreCoupon = true;
              }, 300);
            }
          }
        }).catch(function (rep) {
          setTimeout(function () {
            this.noMoreCoupon = true;
          }, 300);
        });
      },
      moreList() {
        this.loading = true;
        this.noMoreCoupon = true;
        this.clickMoreList();
      },
      //跳转至卡包优惠券详情
      goCouponDetl(params) {
//                  Storage.set("couponInfoExchange", params);
        this.$router.push({
          name: 'couDetail',
          query: {
            type: 'noExchange',
            couponId: params.couponId,
            mchtId: params.mchtId,
            seq: params.seqNo || '',
            usrId: params.usrId || '',
            usrPicId: ''
          }
        });

      },
      //关掉显示卡包里的优惠券的弹窗
      isBackNow() {
        this.$emit("isBack", 'hidden');
        this.isBack = true;
      },
      add(index) {
        //在点击卡券的时候先出栈第一个前一次的点击卡券的下标
        this.allClick.shift();
        //之后在压栈当前点击的卡券下标
        this.allClick.push(index);
        this.currentIndex = index;
        this.cardValuetion = this.myCardList[index].valuation;
        this.cardType = this.myCardList[index].type;//item.type | couponTp
        this.payCardMchtId = this.myCardList[index].mchtId;//用此券来兑换，此券的mchtId
        this.payCardId = this.myCardList[index].couponId;//用此券来兑换，此券的couponId
        this.denomination = this.myCardList[index].denomination;
        this.type = this.myCardList[index].type;
        this.name = this.myCardList[index].name;
        //判断两次点击的是否是同一个卡券
        if (this.allClick[0] != this.allClick[1]) {
          //将父组件传来的卡券金额赋给本地的paySum
          this.paySum = this.buyCardInfo.allPayNum;
          this.useCardNum = 1;
          //调用getSum函数
          this.paySum = this.getSum(this.currentIndex);
        }
        else {
          if (!this.status) {
            if (this.useCardNum < this.myCardList[index].num) {
              this.useCardNum++;
              this.paySum = this.getSum(this.currentIndex);
            }
          }
        }
        //计算手续费
        getData.fee().then(reps => {
          //console.log(reps)
          this.feeArray = JSON.parse(JSON.stringify(reps.content));
          var array = reps.content;
          for (var i = 0; i < array.length; i++) {
            if (array[i].feeValue <= this.cardValuetion * this.useCardNum) {
              this.fee = parseInt(array[i].feeScale * this.cardValuetion * this.useCardNum);
              //.log( '手续费'+this.fee)
              //console.log( '单张手续费'+this.fee/this.useCardNum);
              return
            }
          }
        });
      },
      reduce(index) {
        this.allClick.shift();
        this.allClick.push(index);
        this.currentIndex = index;
        this.cardValuetion = this.myCardList[index].valuation;
        this.cardType = this.myCardList[index].type;
        this.payCardMchtId = this.myCardList[index].mchtId;//用此券来兑换，此券的mchtId
        this.payCardId = this.myCardList[index].couponId;//用此券来兑换，此券的couponId
        this.denomination = this.myCardList[index].denomination;
        this.type = this.myCardList[index].type;
        this.name = this.myCardList[index].name;
        if (this.allClick[0] != this.allClick[1]) {
          this.paySum = this.buyCardInfo.allPayNum;
          this.useCardNum = 0;
          this.paySum = this.getSum(this.currentIndex);
        }
        else {
          if (!this.status) {
            if (this.useCardNum > 0) {
              this.useCardNum--;
              this.paySum = this.getSum(this.currentIndex);
            }
          }
        }
        //计算手续费
        getData.fee().then(reps => {
          //console.log(reps)
          this.feeArray = JSON.parse(JSON.stringify(reps.content));
          var array = reps.content;
          for (var i = 0; i < array.length; i++) {
            if (array[i].feeValue <= this.cardValuetion * this.useCardNum) {
              this.fee = parseInt(array[i].feeScale * this.cardValuetion * this.useCardNum);
              //console.log( '手续费'+this.fee)
              //console.log( '单张手续费'+this.fee/this.useCardNum);
              return this.fee
            }
          }
        });
      },
      getSum(index) {
        // Sum 为总共云券的价值  单价*数量
        var Sum = this.myCardList[index].valuation * this.useCardNum;
        //判断差值
        if (this.buyCardInfo.allPayNum >= Sum) {
          this.theNeed = "还需";
          return this.buyCardInfo.allPayNum - Sum;

        }
        if (this.buyCardInfo.allPayNum < Sum) {
          this.theNeed = "返还";
          this.theShow = '返还';
          return Sum - this.buyCardInfo.allPayNum;
        }
      },
      btnOk() {
        this.$store.commit('changeState', true)
        // Indicator.open('兑换中...');
        //进行兑换
        getData.changeCard({
          'method': 'post', data: {
            "couponId": this.buyCardInfo.couponId,//要买的优惠券Id
            "exchangeCoupon": {
              "ecCouponId": this.payCardId,//用此券去兑换，此券的id
              "ecMchtId": this.payCardMchtId,//用此券去兑换，此券的商户id
              "ecNum": this.useCardNum,//用此券去兑换，用了几张此券
              "ecYunCur": this.myCardList[this.currentIndex].valuation,//用此券去兑换，此券估值
            },
            "mchtId": this.buyCardInfo.buyCardMchtId,//要买的券的商户id
            "num": this.buyCardInfo.buyCardNum,//要买的券的张数
            "owner": this.buyCardInfo.ownerId,//要买的券的拥有者
            "seqNo": this.buyCardInfo.seqNo,//要买的券的挂单流水号
            "yunCur": this.buyCardInfo.allPayNum / this.buyCardInfo.buyCardNum,//要买的券的总价值（张数*面值）
          }
        }, this.userInfo.usrId).then(rep => {
          //console.log(rep);
          if (rep.respCode == "00") {
            // Indicator.close();
            this.exCardInfo = {
              theShow: this.theShow,
              paySum: this.paySum,
              cardValuetion: this.cardValuetion,
              useCardNum: this.useCardNum,
              denomination: this.denomination,
              type: this.type,
              name: this.name,
            };
            Storage.set("exCardInfo", this.exCardInfo);
            if (this.buyCardInfo.pathType == 'tuijian') {
              this.$emit("paySuccess", false);
              this.isBack = true;
            } else {
              this.$router.push({
                name: 'exchangeSuccess',
                query: {
                  exCardInfo: this.exCardInfo,
                  tlrNo: this.tlrNo,
                  scanState: this.scanState,
                  inputAmt: this.inputAmt,
                  inputNoSlae: this.inputNoSlae,
                  inputDeskNum: this.inputDeskNum


                }
              });
            }


          } else {
            Toast({
              message: rep.errorInfo,
              duration: 1000
            });

          }
        })

      },
    },

  }
</script>
<style scoped>
  .shadowBox {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, .8);
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1
  }

  .exchange_btn2 {
    position: fixed;
    bottom: 0;
    left: 0;
    height: 3.9rem;
    width: 100%;
    background: #fff;
    z-index: 3;
  }

  .exchange_btn2 .btn_sure {
    background-color: #ec4e8a;
    color: #fff;
    width: 9.5rem;
    text-align: center;
    margin-left: 1.25rem;
    line-height: 3.9rem;
    font-size: 1rem
  }

  .exchange_btn2 .total {
    text-align: right
  }

  .exchange_btn2 .total_all {
    font-size: .8rem;
    color: #666;
    padding-top: .2rem;
    line-height: .875rem;
  }

  .exchange_btn2 .total_all span {
    color: #ec4e8a
  }

  .total_all_top {
    color: #666;
    font-size: .8rem;
    margin-top: .7rem;
    margin-bottom: .2rem;
  }

  .allContent {
    width: 100%;
    min-height: 33.7rem;
    position: absolute;
    left: 0;
    top: 5rem;
    z-index: 2;
    background: linear-gradient(35deg, #ec4e8a, #f95a7c);
  }

  .cardListTit {
    height: 3.3rem;
    color: #fff;
    text-align: center;
    line-height: 3.3rem;
    border-bottom: 1px solid #d31176
  }

  .cardListTit i {
    position: absolute;
    right: 1.068rem;
  }

  .cardListTit_coupon {
  }

  /*overflow:scroll;height:29.7rem;overflow:scroll;*/
  .cardCard {
    padding: 0 .5rem .3rem .5rem;
    height: 13.5rem;
  }

  .box {
    height: 2rem;
    width: 100%;
  }

  .cardCard_tit {
    height: 2.6rem;
    color: #fff;
    line-height: 2.6rem;
    padding-left: .667rem;
  }

  .cardBg2 {
    position: absolute;
    top: 0;
    left: .3rem;
    z-index: 1;
    box-sizing: border-box;
    padding: .6rem;
    width: -webkit-calc(100% - .6rem);
    height: 10.9rem;
    border-radius: .2rem;
  }

  .bgLine {
    position: absolute;
    top: 6.8rem;
    left: 0;
    z-index: 2;
    width: 100%;
    background-color: rgb(246, 87, 127);
  }

  .bgLine img {
    width: 98%;
    transform: translateX(1%)
  }

  .cardBg1 {
    height: 0;
  }

  .card_btn {
    top: 8rem;
  }

  .card_btn p:nth-child(1) {
    float: left;
    margin-left: 1rem;
    color: #666;
  }

  .card_btn p:nth-child(1) span:nth-child(1) {
    color: #ec4e8a;
    font-weight: bold;
    font-size: 1.2rem;
  }

  .card_btn p:nth-child(2) {
    float: right;
    margin-right: 1rem;
  }

  .coupon_num {
    display: inline-block;
    float: right;
    color: #333;
    font-weight: bold;
    width: 2.16rem;
    background: #f2f2f2;
    border-radius: .1rem;
    height: 2.2rem;
    text-align: center
  }

  .coupon_num:nth-child(1) {
    font-size: 1.8rem;
    color: #999;
    line-height: 2.2rem;
  }

  .coupon_num:nth-child(2) {
    margin: 0 .43rem 0 .43rem;
    color: #333;
    width: 3.2rem;
  }

  .coupon_num:nth-child(3) {
    font-size: 1.2rem;
    color: #999;
    line-height: 2.2rem;
  }

  .card_info {
    position: relative
  }

  .card_info i {
    position: absolute;
    right: .667rem;
    top: 2.1rem;
    color: #666;
  }

  .noCard {
    color: #fff;
    text-align: center;
    margin-top: 5rem;
  }

  .last_box {
    height: 3.8rem;
    width: 100%;
  }
</style>
